const express = require('express')
const history = require('connect-history-api-fallback')
const http = require('http')
const urlParse = require('url')
const qs = require('qs')
const axios = require('axios')

const wechatConfig = require('./config')
const utils = require('./utils')

const app = express()
app.use(history())
app.use(express.static('public'))
const server = http.createServer(app)
const PORT = 80
server.listen(PORT, function () {
    console.log('HTTP Server is running on: http://localhost:%s', PORT)
})

// 测试使用
app.get('/api/test', function (req, res) {
    const realUrl = (req.connection.encrypted ? 'https' : 'http') + '://' + req.headers.host + req.url;
    console.log(urlParse.parse(realUrl, true))

    console.log(req.headers.referer)
    res.send('api can use')
})

// 验证信息
app.get('/api/wechat', function (req, res) {
    if (verifySignature(req.query)) {
        res.send(req.query.echostr)
        return
    }
    res.send('error')
})

function verifySignature(query) {
    console.log('接收参数', query['timestamp'], query['nonce'], query.signature)
    const keys = [
        wechatConfig.wechatToken,
        query['timestamp'],
        query['nonce'],
    ]
    let str = keys.sort().join('')
    str = utils.genSHA1(str)

    return str === query.signature
}

// 获取openid
app.get('/api/get-openid', function (req, res) {
    if (req.query.code == undefined) {
        return
    }

    let url = ''
    let params = {
        appid: wechatConfig.appId,
        secret: wechatConfig.appSecret,
        code: req.query.code,
        grant_type: 'authorization_code'
    }
    params = qs.stringify(params)
    url = wechatConfig.oAuthUrl + '?' + params
    console.log(url)
    axios.get(url)
        .then(function (response) {
            res.send(response.data.openid)
        })
        .catch(function (error) {
            console.log(error)
            res.send('error')
        })
})

// 获取签名
app.get('/api/get-signature', function (req, res) {
    let url = ''

    // if (wechatConfig.signature == '') {
        // 获取access_token
        let params = {
            grant_type: 'client_credential',
            appid: wechatConfig.appId,
            secret: wechatConfig.appSecret,
        }
        params = qs.stringify(params)
        console.log(url)
        url = wechatConfig.accessTokenUrl + '?' + params
        axios.get(url)
            .then(function (response) {
                wechatConfig.access_Token = response.data.access_token
                // 获取ticket
                params = {
                    access_token: response.data.access_token,
                    type: 'jsapi'
                }
                params = qs.stringify(params)
                url = wechatConfig.ticketUrl + '?' + params
                axios.get(url)
                    .then(function (response) {
                        wechatConfig.jsapi_ticket = response.data.ticket
                        // 生成signature
                        // const realUrl = (req.connection.encrypted ? 'https': 'http') + '://' + req.headers.host + req.url;
                        const realUrl = req.headers.referer
                        const s = generateSignature(realUrl, wechatConfig.access_Token, wechatConfig.jsapi_ticket)
                        wechatConfig.timestamp = s['timestamp']
                        wechatConfig.nonceStr = s['nonceStr']
                        wechatConfig.signature = s['signature']

                        let result = {
                            timestamp: s['timestamp'],
                            nonceStr: s['nonceStr'],
                            signature: s['signature']
                        }
                        result = JSON.stringify(result)
                        console.log(`result:${result}`)
                        res.send(result)
                    })
                    .catch(function (error) {
                        console.log(error)
                        res.send('error')
                    })
            })
            .catch(function (error) {
                console.log(error)
                res.send('error')
            })
    // } else {
    //     let result = {
    //         timestamp: wechatConfig.timestamp,
    //         nonceStr: wechatConfig.nonceStr,
    //         signature: wechatConfig.signature
    //     }
    //     result = JSON.stringify(result)
    //     console.log(`result:${result}`)
    //     res.send(result)
    // }
})

function generateSignature(url, accessToken, ticket) {
    const ret = {
        jsapi_ticket: ticket,
        nonceStr: utils.nonceStr(),
        timestamp: utils.timestamp(),
        url: utils.normalizeUrl(url),
    };
    const originalStr = utils.paramsToString(ret);
    console.log(`string1:${originalStr}`)
    ret.signature = utils.genSHA1(originalStr);
    console.log('utils:', ret)
    return ret;
}

// 获取用户信息
app.get('/api/get-userinfo', function (req, res) {
    if (req.query.code == undefined) {
        return
    }

    let url = ''
    let params = {
        appid: wechatConfig.appId,
        secret: wechatConfig.appSecret,
        code: req.query.code,
        grant_type: 'authorization_code'
    }
    params = qs.stringify(params)
    url = wechatConfig.oAuthUrl + '?' + params
    console.log(url)
    axios.get(url)
        .then(function (response) {
            console.log(response.data)
            wechatConfig.auth_access_token = response.data.access_token
            wechatConfig.auth_refresh_token = response.data.refresh_token
            wechatConfig.auth_openid = response.data.openid
            wechatConfig.auth_scope = response.data.scope

            params = {
                access_token: response.data.access_token,
                openid: response.data.openid,
                lang: 'zh_CN'
            }
            params = qs.stringify(params)
            url = wechatConfig.userInfoUrl + '?' + params
            axios.get(url)
                .then(function (response) {
                    console.log(response.data)
                    res.send(JSON.stringify(response.data))
                })
                .catch(function (error) {
                    console.log(error)
                    res.send('error')
                })
        })
        .catch(function (error) {
            console.log(error)
            res.send('error')
        })
})
